package com.eaoa.uc.pubmessage.bo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.eaoa.base.EABaseBusinessObject;
import com.eaoa.constants.PubAccountConstants;
import com.eaoa.constants.PubConstantsType;
import com.eaoa.constants.PubMessageConstants;
import com.eaoa.dao.pub.PubMessageDAO;
import com.eaoa.query.pub.PubAccountQuery;
import com.eaoa.utils.ConstantsContainer;
import com.eaoa.vo.pub.PubAccount;
import com.eaoa.vo.pub.PubMessage;
import com.stony.core.util.CoreUtils;

public class MessageCommitBO extends EABaseBusinessObject {

	private Long messageno;

	private static PubMessageDAO messageDAO = new PubMessageDAO();
	private static ConstantsContainer instance = ConstantsContainer.getInstants();
	
	public MessageCommitBO(Long messageno) {
		super();
		this.messageno = messageno;
	}

	protected void performBusinessLogic() {
		
		PubMessage message = (PubMessage) messageDAO.loadAndLock(messageno);
		if(message.getReceivers()!=null){
			
			List<Long> receivernos = getReceivernos(message.getReceivers());
			
			List<PubMessage> pubMessages = new ArrayList<PubMessage>();
			
			pubMessages.add(message);
			message.setStatus(PubMessageConstants.MESSAGE_STATUS_RUN);
			message.setSenderdate(new Date());
			
			for(int i=0; i<receivernos.size(); i++){
				Long receiverno = (Long)receivernos.get(i);
				
				PubMessage messageClone = message.clone();
				messageClone.setMessageno(null);
				messageClone.setReceiver(receiverno);
				messageClone.setReceivername(instance.getLabel(PubConstantsType.HREmployee, receiverno.toString()));
				messageClone.setStatus(PubMessageConstants.MESSAGE_STATUS_NRD);
				pubMessages.add(messageClone);

			}
			
			messageDAO.saveOrUpdateBatch(pubMessages);
		}

	}
	
	private List<Long> getReceivernos(String receivers){
		List<Long> result = new ArrayList<Long>();
		if(receivers.indexOf(PubMessageConstants.RECEIVERS_ALL)!=-1){
			PubAccountQuery query = new PubAccountQuery();
			query.setIslock("N");
			query.execute();
			List accounts = query.getResults(); 
			for(int i=0; i<accounts.size(); i++){
				PubAccount account = (PubAccount)accounts.get(i);
				result.add(account.getAccountno());
			}
		}else if(receivers.indexOf(PubMessageConstants.RECEIVERS_ALL_CUSTOMERS)!=-1){
			PubAccountQuery query = new PubAccountQuery();
			query.setIslock("N");
			query.setAccounttype(PubAccountConstants.ACCOUNTTYPE_OUTER);
			query.execute();
			List accounts = query.getResults(); 
			for(int i=0; i<accounts.size(); i++){
				PubAccount account = (PubAccount)accounts.get(i);
				result.add(account.getAccountno());
			}
		}else{
			String[] receivernos = receivers.split(",");
			for(int i=0; i<receivernos.length; i++){
				Long receiverno = CoreUtils.parseLong(receivernos[i]);
				result.add(receiverno);
			}
		}
		
		return result;
	}

}
